<template>
  <div class="main_div">
    <div class="title_div">
       <span style="margin-left: 60px; color: white; font-size: larger; font-weight: 900;">{{cname}}</span>
       <span style="margin-right: 60px;">
         <el-button type="success" @click="openMedia">共享屏幕</el-button>
         <el-button type="danger" @click="closeMedia">结束共屏</el-button>
       </span>
    </div>

    <div class="body_div">
      <!-- 直播播放器 -->
      <div class="video_div">
        <video ref="localVideo" autoplay="autoplay" controls="controls" class="video_cls"></video>
      </div>
      <!-- 聊天div -->
      <div class="other_div">
        <!-- 学生列表 -->
        <div class="stu_cls">
          <div style="width: 100%; height: 10%; color: white; display: flex; flex-direction: column; justify-content: center; align-items: center;">
            在线人数：{{number}}
          </div>
        </div>
        <!-- 聊天框 -->
        <div class="im_cls">
          <div ref="im_div" style="background-color: white; width: 100%; height: 80%; text-align: left;">
          </div>
          <div style="width: 100%; height: 20%; display: flex; flex-direction: row; align-items: center; justify-content: space-evenly;">
            <el-input style="width: 60%;" placeholder="请输入消息内容"></el-input>
            <el-button type="primary">发送</el-button>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
  import kurentoUtils from 'kurento-utils'

  export default {
    data(){
      return {
        //需要直播的课程id号
        cid: this.$route.params.cid,
        //课程名称
        cname: this.$route.params.cname,
        //直播间在线人数
        number: 0,
        //本地的媒体流
        media: {
          //视频媒体流
          video: null,
          //音频媒体流
          audio: null
        },
        //和KMS服务器远程连接对象
        webRtcPeer: null
      }
    },
    methods: {
      //开启屏幕共享，打开本地的媒体，将媒体流传递到KMS服务器上
      async openMedia(){
        //开启本地媒体流
        this.media.video = await navigator.mediaDevices.getDisplayMedia();
        // this.media.audio = await navigator.mediaDevices.getUserMedia({video:false, audio:true});

        //获取视频轨道
        var videoTrack = this.media.video.getVideoTracks()[0];
        //设置优先级 - 流畅度优先
        videoTrack.contentHint = "motion";

        //创建KMS的客户端对等连接对象
        //准备相关参数
        var option = {
          //本地的video标签对象
          localVideo: this.$refs.localVideo,
          //设置想要直播的媒体流
          videoStream: this.media.video,
          // audioStream: this.media.audio,
          //ice候选者的回调方法
          //onicecandidate: this.onIceCandidate,
          //stun服务器地址
          configuration: {
            iceServers: [
              {
                urls: "stun:110.41.133.47:3478"
              },{
                urls: "turn:110.41.133.47:3478",
                username: "kurento",
                credential: "kurento"
              }
            ]
          }
        };

        //创建kurento的RTC连接, 直播方
        this.webRtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendonly(option, (error) => {
            //回调方法
            if(error) {
              //存在异常
              return console.error(error);
            }

            //成功，创建提案
            this.webRtcPeer.generateOffer(this.onOfferPresenter);
        });
      },
      //客户端生成提案SDP的回调方法
      onOfferPresenter(error, offerSdp){
        if(error){
					//提案创建有问题
					return console.error(error);
			  }
				console.log("创建好了本地的提案：", offerSdp);

				//提案创建成功，将提案发送给信令服务器
				var offerMsg = {
					action: "offerSdp",
					role: "master",
          cid: this.cid,
					msg: offerSdp
				}
        //将直播方的提案信息，发送给信令服务器，由信令服务器转发给KMS服务器
				this.$.sendMsg(offerMsg);
      },
      //关闭本地直播
      closeMedia(){

      },
      //连接信令服务器后的执行方法
      wsOpenHandler(){
        //注册的动作，将主播的信息和课程信息，注册到信令服务器上，课程号就是房间号
        var registerMsg = {
          action: "register",//注册的消息
          role: "master",//master代表主播
          cid: this.cid,//直播的课程id
          cname: this.cname,//课程名称
          token: this.$.getUserToken()//主播的令牌信息-身份信息
        };
        //发送给信令服务器
        this.$.sendMsg(registerMsg);
      },
      //信令服务器传递数据时执行的方法
      wsMsgHandler(msg){
        switch(msg.action) {
          case "authError":
            alert("身份认证失败，请重新登录后再开始上课！");
            break;
          case "registerSucc":
            this.showInfo2Div("系统", "聊天服务器连接成功....", "red");
            break;
          case "roomInfoError":
            this.showInfo2Div("系统", "房间信息有误....", "red");
            break;
          case "answerSdp":
            this.webRtcPeer.processAnswer(msg.msg);
            break;
          case "iceCandidate":
            this.webRtcPeer.addIceCandidate(msg.msg);
            break;
          case "number":
            //人数更新
            this.number = msg.msg;
            break;
        }
      },
      //将指定的文本展示到聊天框中
      showInfo2Div(source, content, color){
        var text = "<div style='color: " + (color ? color : 'black') + "'>【" + source + "】:" + content + "</div>";
        this.$refs.im_div.innerHTML += text;
      },
      //监听页面卸载
      solveBeforeUnload(){
        //给信令服务器发送消息
        var closeMsg = {
          action: "close",
          cid: this.cid
        };

        this.$.sendMsg(closeMsg);
      }
    },
    mounted(){
      //页面加载时触发！！
      this.$.wsInit({
        onopen: this.wsOpenHandler,
        onmessage: this.wsMsgHandler
      });

      //添加页面卸载前的监听事件
      window.addEventListener('beforeunload', this.solveBeforeUnload);
    }
  }
</script>

<style scoped="scoped">

  .main_div {
    width: 100%;
    height: 100%;
    background-color: gray;
  }

  .title_div {
    width: 100%;
    height: 10%;
    background-color: dimgray;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }

  .body_div {
    width: 100%;
    height: 90%;
    display: flex;
    flex-direction: row;
  }

  .video_div {
    height: 100%;
    flex: 3;
  }

  .video_cls {
    display:block;
    width:100%;
    height:100%;
    margin:auto;
    font-size:24px;
    object-fit: fill;
  }

  .other_div {
    height: 100%;
    flex: 1;
  }

  .stu_cls {
    width: 100%;
    height: 50%;
  }

  .im_cls {
    width: 100%;
    height: 50%;
  }

</style>
